import React, { useState,useEffect } from 'react';  
import { Tabs, Collapse, Table , Button, Modal, Form, Select ,Input,message} from 'antd';  
import { useTranslation } from 'react-i18next';  
import { list,delmark,addmark,editmark,getIngredientInfoById,getIngredientSubjectTestById,comparisonIngredient,importIngredientInfoCheck,importIngredientInfoSave} from "@/api/modules/litermark";
import { getInfo } from "@/api/login/ssoLogin";
const { TabPane } = Tabs;  
const { Panel } = Collapse;  
const { Option } = Select;  


const MyTabsComponent = ({ tabData, tabSubjectLevel1,formId,reportList }) => {  
  const { t } = useTranslation();  
  const [activeKey, setActiveKey] = useState(tabData[0].id); // 假设第一个tab是默认选中的  
  const [activeNames, setActiveNames] = useState([]); // 初始没有展开的Collapse面板  
  const [visible, setVisible] = useState(false); // 控制Modal的显示与隐藏  
  const [editingRecord, setEditingRecord] = useState(null); // 保存当前编辑的记录  
  const [form] = Form.useForm(); // 创建表单实例 
  const [newData,setNewData] = useState([]);
  const [newtabSubjectLevel1,setNewtabSubjectLevel1] = useState([]);
  const [newreportList,setNewReportList] = useState([]);
  const [viewStatus, setViewStatus] = useState(false); // 加载状态 


    // 初始化数据  
    useEffect(() => {  
      getInfo().then(res=>{
        console.log(res,'res')
        let data = res.data
        data.roles.forEach((item)=>{
          if(item == "Formulator"){
            setViewStatus(true)
          }
        })
      }) 
      console.log(reportList,'reportList')
      setNewData(tabData)
      setNewtabSubjectLevel1(tabSubjectLevel1)
      setNewReportList(reportList)
    }, []);  

  // 渲染Table的列  
  const baseColumns = [  
    {  
      title: t('searchDetail.ToxicologyEndpointSub'),  
      dataIndex: 'subjectLevel2Cn', // 假设这是数据中的字段名  
      key: 'subjectLevel2Cn', 
      render: (text, record) => {  
        // record 对应于每一行的数据，这里我们假设它是名为 row 的对象  
        // 使用 record.zySafetySubjectDef.subjectLevel2Cn 来获取需要显示的值  
        return record.zySafetySubjectDef ? record.zySafetySubjectDef.subjectLevel2Cn : '';  
        // 如果 record.zySafetySubjectDef 可能不存在，使用空字符串或适当的默认值  
      },  
    },  
    {  
      title: t('searchDetail.ToxicologyEndpointSub'),  
      dataIndex: 'subjectLevel2', // 假设这是数据中的字段名  
      key: 'subjectLevel2',  
      render: (text, record) => {  
        return record.zySafetySubjectDef ? record.zySafetySubjectDef.subjectLevel2 : '';  
      },  
    }, 
    {  
      title: t('value'),  
      dataIndex: 'resultCn', // 假设这是数据中的字段名  
      key: 'resultCn',  
      render: (text, record) => {  
        return record.zySafetyIngredientSubjectTestResult ? record.zySafetyIngredientSubjectTestResult.resultCn : '';  
      }, 
    },  
    {  
      title: t('unit'),  
      dataIndex: 'unit', // 假设这是数据中的字段名  
      key: 'unit',  
      render: (text, record) => {  
        return record.zySafetyIngredientSubjectTestResult ? record.zySafetyIngredientSubjectTestResult.unit : '';  
      }, 
    },  
    {  
      title: t('link'),  
      dataIndex: 'link', // 假设这是数据中的字段名  
      key: 'link',  
      render: (text, record) => {  
        return record.zySafetyIngredientSubjectTestResult ? record.zySafetyIngredientSubjectTestResult.link : '';  
      }, 
    },  
    {  
      title: t('reportView'),  
      dataIndex: 'reference', // 假设这是数据中的字段名  
      key: 'reference',  
      render: (text, record) => {  
        return record.zySafetyIngredientSubjectTestResult ? record.zySafetyIngredientSubjectTestResult.reference : '';  
      }, 
    },  
    {  
      title: t('fulu'),  
      dataIndex: 'comment', // 假设这是数据中的字段名  
      key: 'comment',  
      render: (text, record) => {  
        return record.zySafetyIngredientSubjectTestResult ? record.zySafetyIngredientSubjectTestResult.comment : '';  
      }, 
    },  
    {  
      title: t('remark'),  
      dataIndex: 'remark', // 假设这是数据中的字段名  
      key: 'remark',  
      render: (text, record) => {  
        return record.zySafetyIngredientSubjectTestResult ? record.zySafetyIngredientSubjectTestResult.remark : '';  
      }, 
    }, 
    // ... 其他列定义  
    {  
      title: t('action'),  
      key: 'action',  
      fixed: 'right' as 'right',
      width:120,
      render: (_, record) => (  
        <div>  
        {viewStatus ? null : (
            <>
              <Button type='primary' size="small" onClick={() => handleEdit(record)}>{t('edit')}</Button>  
              <Button danger size="small" style={{marginLeft:'10%'}} onClick={() => handleDelete(record)}>{t('delete')}</Button>  
            </>
          )}
        </div>  
      ),  
    },  
  ];  

   // 假设的编辑和删除函数（需要您实现具体的逻辑）
 
   const handleEdit = (record) => { 
       // 编辑逻辑  
       form.resetFields()  
    getIngredientInfoById(formId).then(res=>{
      let reportCIR = []
      let reportLiterature = []
      const reportData = res.data.data.reports
      reportData.map(item=>{
        if(item.origin == 'CIR' || item.origin ==''){
          reportCIR.push(item)
        }else{
          reportLiterature.push(item)
        }
    })
    form.setFieldsValue({ 
      reportCIR:reportCIR,
      reportLiterature:reportLiterature,
    })
    if(record.zySafetyIngredientSubjectTestResult==null){
      form.setFieldsValue({  
        id: undefined, // 假设form.value.id是某个状态或props的值  
        // ... 其他字段  
        safetyIngredientId:formId,
        safetySubjectDefId:record.zySafetySubjectDef.id,
        subjectLevel2Cn:record.zySafetySubjectDef.subjectLevel2Cn,
        recodsubjectLevel2:record.zySafetySubjectDef.subjectLevel2,
        recodresultEn:null,
        recodresultCn: null,
        recodresults_link :null,
        recodresults_reference: [],
        recodresults_remark:null,
        recodresults_comment:null,
        recodunit:null,
        recodsubjectType : record.zySafetySubjectDef.subjectType,
        safetyTestDefId:activeKey,
      }); 
      if(record.zySafetySubjectDef.subjectLevel1Cn=='CIR'){
        form.setFieldsValue({ 
          origin:'CIR'
         })      
        }else{
          form.setFieldsValue({ 
            origin:'Literature'
           }) 
        }
      }else{ 
        form.setFieldsValue({ 
                id:record.zySafetyIngredientSubjectTestResult.id,
                calculation:record.zySafetySubjectDef.calculation,
                subjectNo:record.zySafetySubjectDef.subjectNo,
                level1Seq:record.zySafetySubjectDef.level1Seq,
                level2Seq:record.zySafetySubjectDef.level2Seq,
                remark:record.zySafetySubjectDef.remark,
                subjectLevel1Cn:record.zySafetySubjectDef.subjectLevel1Cn,
                subjectLevel1En:record.zySafetySubjectDef.subjectLevel1En,
                subjectLevel2:record.zySafetySubjectDef.subjectLevel2,
                subjectLevel2Cn:record.zySafetySubjectDef.subjectLevel2Cn,
                subjectType:record.zySafetySubjectDef.subjectType,
                safetyIngredientId:record.zySafetyIngredientSubjectTestResult.safetyIngredientId,
                safetySubjectDefId:  record.zySafetySubjectDef.id,
            
                resultEn:record.zySafetyIngredientSubjectTestResult.resultEn,
                resultCn:record.zySafetyIngredientSubjectTestResult.resultCn,
                results_link :record.zySafetyIngredientSubjectTestResult.link,
                results_comment :record.zySafetyIngredientSubjectTestResult.comment,

                results_reference: JSON.parse(record.zySafetyIngredientSubjectTestResult.reference),
                results_remark:record.zySafetyIngredientSubjectTestResult.remark,
                unit:record.zySafetyIngredientSubjectTestResult.unit,
                safetyTestDefId:activeKey,
         })    
                if(record.zySafetySubjectDef.subjectLevel1Cn=='CIR'){
                  form.setFieldsValue({ 
                    origin:'CIR'
                    })
                }else{
                     form.setFieldsValue({ 
                      origin:'Literature'
                      })
                }
            }  
            const data = form.getFieldsValue()
    console.log(data,'form')
    setVisible(true); // 打开Modal  
    }) 
    // setEditingRecord(record); // 设置要编辑的记录 
    
  };  

  
  
  const handleDelete = (record) => {  
    // 删除逻辑  
    let inciIds = []
    inciIds.push(record.zySafetyIngredientSubjectTestResult.id)
    Modal.confirm({  
      title: 'Confirm Delete',  
      content: 'Please confirm to DELETE SELECTED RECORDS!',  
      onOk() {  
        delmark(inciIds).then(res=>{
            getIngredientSubjectTestById(formId).then(response=>{
              const newUniqueSubjectLevels = new Set(); 
              let data =response.data.data
              setNewData(data)
              data.forEach(item => {  
                item.subjectTestRespList.forEach(subItem => {  
                  const subjectLevel = `${subItem.zySafetySubjectDef.subjectLevel1Cn}/${subItem.zySafetySubjectDef.subjectLevel1En}`;  
                  newUniqueSubjectLevels.add(subjectLevel); // 使用Set来自动去重  
                });  
              });  
              const uniqueSubjectLevelsArray = Array.from(newUniqueSubjectLevels); 
              setNewtabSubjectLevel1(uniqueSubjectLevelsArray)
              message.success("Success")
          })
        }) 
      },  
    }); 
  };  
    // Modal的关闭处理函数  
    const handleModalClose = () => {  
      setVisible(false);  
      setEditingRecord(null); // 清空编辑的记录  
    };  

    const handleChange = (value) => {  
      // 这里可以处理值的变化，但根据你的需求，你可能不需要这个处理函数  
      console.log(value);  
  };  
    
    // 假设的表单提交处理函数（这里只是一个空函数，你需要根据实际需求实现）  
    const handleFormSubmit = (values) => {  
      // ... 提交表单的代码，可能是更新记录到后端  
      if (values.id != undefined) {
        let ref_string=''
        let ref_json=values.results_reference
        ref_string=JSON.stringify(ref_json);
        let data={
           id:values.id,
           resultEn:values.resultEn,
           resultCn:values.resultCn,
           reference:ref_string,
           remark:values.results_remark,
           link: values.results_link,
           unit:values.unit,
           comment:values.results_comment,
       }
        editmark(data).then(response => {
          getIngredientSubjectTestById(formId).then(response=>{
            const newUniqueSubjectLevels = new Set(); 
            let data =response.data.data
            setNewData(data)
            data.forEach(item => {  
              item.subjectTestRespList.forEach(subItem => {  
                const subjectLevel = `${subItem.zySafetySubjectDef.subjectLevel1Cn}/${subItem.zySafetySubjectDef.subjectLevel1En}`;  
                newUniqueSubjectLevels.add(subjectLevel); // 使用Set来自动去重  
              });  
            });  
            const uniqueSubjectLevelsArray = Array.from(newUniqueSubjectLevels); 
            setNewtabSubjectLevel1(uniqueSubjectLevelsArray)
            message.success("Success")
          })
        });
      }else{
        let ref_json=values.results_reference
        let ref_string=JSON.stringify(ref_json);
        let data={
            resultEn:values.resultEn,
            resultCn:values.resultCn,
            reference:ref_string,
            remark:values.results_remark,
            link: values.results_link,
            comment:values.results_comment,
            unit:values.unit,
            safetySubjectDefId: values.safetySubjectDefId,
            safetyTestDefId: values.safetyTestDefId,
            safetyIngredientId:values.safetyIngredientId,
        }
      addmark(data).then(response => {
        getIngredientSubjectTestById(formId).then(response=>{
          const newUniqueSubjectLevels = new Set(); 
          let data =response.data.data
          setNewData(data)
          data.forEach(item => {  
            item.subjectTestRespList.forEach(subItem => {  
              const subjectLevel = `${subItem.zySafetySubjectDef.subjectLevel1Cn}/${subItem.zySafetySubjectDef.subjectLevel1En}`;  
              newUniqueSubjectLevels.add(subjectLevel); // 使用Set来自动去重  
            });  
          });  
          const uniqueSubjectLevelsArray = Array.from(newUniqueSubjectLevels); 
          setNewtabSubjectLevel1(uniqueSubjectLevelsArray)
          message.success("Success")
        })
     });
      }
      handleModalClose(); // 提交后关闭Modal  
    };  
  // Modal组件的内容  
  const modalContent = (  
    <Modal  
      title="编辑/Edit"  
      visible={visible}  
      onCancel={handleModalClose}  
      footer={null} // 自定义底部，不显示默认的确定和取消按钮  
    >  
      <Form  
        form={form}  
        name="edit_form"  
        onFinish={handleFormSubmit}  
        layout="vertical"
      >  
           <Form.Item  
                name="id"  
                label="id" 
                hidden

            >  
                <Input disabled/>  
            </Form.Item> 
            <Form.Item  
                name="safetyIngredientId"  
                label="safetyIngredientId"  
                hidden
            >  
                <Input disabled/>  
            </Form.Item> 
            <Form.Item  
                name="safetySubjectDefId"  
                label="safetySubjectDefId" 
                hidden
            >  
                <Input disabled/>  
            </Form.Item> 
            <Form.Item  
                name="safetyTestDefId"  
                label="safetyTestDefId" 
                hidden
            >  
                <Input disabled/>  
            </Form.Item> 
        {/* 添加你的表单项，例如： */}  
        <Form.Item  
          name="resultCn"  
          label={t('value')}  
        >  
           <Input />  
        </Form.Item>  
        <Form.Item  
          name="unit"  
          label={t('unit')}  
        >  
          <Select>  
            <Option value="mg">mg</Option>  
            <Option value="g">g</Option>  
            <Option value="kg">kg</Option>  
            <Option value="ml">ml</Option>  
            <Option value="l">l</Option>  
            <Option value="%">%</Option>  
          </Select>  
        </Form.Item>  
        {/* 其他表单项... */}  
        <Form.Item  
          name="results_link"  
          label={t('link')} 
        >  
           <Input />  
        </Form.Item> 
        <Form.Item  
          name="results_reference"  
          label={t('reportView')}  
        >  
            <Select mode="multiple"  onChange={handleChange}>  
                {newreportList.map((item) => (  
                    <Option key={item.id} value={item.origin === 'CIR' ? item.dateReference : item.reference}>  
                        {item.name}  
                    </Option>  
                ))}  
            </Select>  
        </Form.Item> 
        <Form.Item  
          name="results_comment"  
          label={t('fulu')} 
        >  
           <Input.TextArea />  
        </Form.Item> 
        <Form.Item  
          name= "results_remark"
          label={t('remark')} 
        >  
           <Input.TextArea />  
        </Form.Item> 
        {/* 自定义提交按钮 */}  
        <Form.Item>  
          <Button type="primary" htmlType="submit">  
            提交  
          </Button>  
        </Form.Item>  
      </Form>  
    </Modal>  
  ); 
  
  // 假设 subjectTestRespList 中的每个对象都有一个字段用于与 subjectLevel 匹配  
  const filterDataSourceBySubjectLevel = (subjectTestRespList, subjectLevel) => {  
    // 使用模板字符串或字符串连接来拼接两个字段的值  
    // 假设 subjectLevel 是形如 "中文等级/英文等级" 的字符串  
    return subjectTestRespList.filter(item => {  
        // 注意：这里假设 subjectLevel 的格式与拼接后的格式完全匹配  
        // 如果 subjectLevel 可能有额外的空格或格式不同，你可能需要使用 trim() 或其他方法来规范化字符串  
        const combinedLevel = `${item.zySafetySubjectDef.subjectLevel1Cn}/${item.zySafetySubjectDef.subjectLevel1En}`;  
        return combinedLevel === subjectLevel;  
    });  
};
  // 渲染Tabs和Collapse组件  
  return (  
    <div>
    <Tabs type='card' defaultActiveKey={activeKey} onChange={key => setActiveKey(key)}>  
      {newData.map((item) => (  
        <TabPane  
          tab={`${item.testLevel1Cn}/${item.testLevel1En}`}  
          key={item.id}  
        >  
          <Collapse  
            activeKey={activeNames}  
            onChange={keys => setActiveNames(Array.isArray(keys) ? keys : [keys as string])} 
          >  
            {newtabSubjectLevel1.map((subjectLevel, idx) => (  
              <Panel  
                header={subjectLevel}  
                key={idx}  
              >  
                <Table  
                  dataSource={filterDataSourceBySubjectLevel(item.subjectTestRespList, subjectLevel)} // 筛选与 subjectLevel 匹配的数据  
                  columns={baseColumns}  
                  rowKey={(record) => record.id} // 假设每条记录都有一个唯一的id  
                  pagination={false}
                  bordered  
                  scroll={{ x: 'max-content' }} // 或者使用具体的像素值，如 '1000px' 
                />  
              </Panel>  
            ))}  
          </Collapse>  
        </TabPane>  
      ))}  
    </Tabs>  
    {modalContent}  
    </div>

  );  
  
  
};  
  
export default MyTabsComponent;